package com.zjw.study.thread04_sharedata;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程范围内变量共享
 * @author Administrator
 *
 */
public class SingleShare {
	//声明变量，并初始化
	private static int data = 0;
	
	public static void main(String[] args) {
		SingleShare stu = new SingleShare();
//		stu.share01();
		stu.share02();
	}
	
	/**
	 * 提出问题，第二次或第三次执行getA获取的可能是第一次的值
	 */
	void share01() {
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					data ++;
					System.out.println(Thread.currentThread().getName() + "：" + data);
					new A().getA();
					new B().getB();
				}
			}).start();
		}
	}
	
	//声明集合用以存储每次线程对应的值
	private Map<Thread, Integer> threadData = new HashMap<>();
	
	/**
	 * 解决线程内变量共享中share01的问题
	 */
	void share02() {
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					//声明新变量，解决线程内变量共享问题
					int data = SingleShare.data ++;
					System.out.println(Thread.currentThread().getName() + "：" + data);
					threadData.put(Thread.currentThread(), data);
					new C().get();
					new D().get();
				}
			}).start();
		}
	}
	
	
	class A {
		void getA() {
			System.out.println("A " + Thread.currentThread().getName() + " data=" + data);
		}
	}
	class B {
		void getB() {
			System.out.println("B " + Thread.currentThread().getName() + " data=" + data);
		}
	}
	class C {
		void get() {
//			System.out.println("C " + Thread.currentThread().getName() + " data=" + data);
			System.out.println("C " + Thread.currentThread().getName() + " data=" + threadData.get(Thread.currentThread()));
//			System.out.println("C " + Thread.currentThread().getName() + " data=" + data + "，threadData=" + threadData.get(Thread.currentThread()));
		}
	}
	class D {
		void get() {
//			System.out.println("D " + Thread.currentThread().getName() + " data=" + data);
			System.out.println("D " + Thread.currentThread().getName() + " data=" + threadData.get(Thread.currentThread()));
//			System.out.println("D " + Thread.currentThread().getName() + " data=" + data + "，threadData=" + threadData.get(Thread.currentThread()));
		}
	}

}
